var cfg = require('../../utils/cfg');
// var socketUtil = require('../../utils/socketUtil');

var app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo: {},
    joinCount: 0,
    timeWaitFun: {},
    count: 0,
    waitPic: '/images/wait1.png',
    waitText: '等待参与',
    modelType: 1,
    showStart: '.hide',
    joinUsers: [],
    roomTicket: '',
    roomMaster: '',
    masterAva: '',
    joined : false

  },

  waitUser: function () {
    let that = this;
    that.data.timeWaitFun = setInterval(function () {
      console.log('>>>>>wait...' + that.data.count);
      let waitPic = that.data.count % 2 == 0 ? '/images/wait1.png' : '/images/wait2.png';
      let waitText = that.data.count % 2 == 0 ? '等待开始...' : '等待开始. .';
      that.data.count += 1;
      that.setData({ waitPic: waitPic });
      that.setData({ waitText: waitText });
    }, 1000);
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var _self = this;
    _self.setData({
      userInfo: app.globalData.userInfo
    })

    let roomTicket = options.roomTicket;
    let roomMaster = options.openId;
    let masterAva = options.masterAva;
    console.log('>>>>>头像' + masterAva);

    _self.setData({
      userInfo: app.globalData.userInfo,
      roomTicket: roomTicket,
      roomMaster: roomMaster,
      masterAva: masterAva
    })

    wx.setStorageSync('roomTicket', options.roomTicket);

    if (roomMaster == wx.getStorageSync('loginUser').openId) {
      wx.redirectTo({
        url: '/pages/moreReady/moreReady?modelType=1',
        success: function () {

        },
        fail: function () {

        }
      });
    }

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    let that = this;
    if (!wx.getStorageSync('userInfo')) {
      wx.redirectTo({
        url: '/pages/welcome/welcome?fromId=1002&roomTicket=' + that.data.roomTicket + '&openId=' + that.data.roomMaster + '&masterAva=' + that.data.masterAva,
        success: function () {
          console.log('跳转到welcome页面');
        },
        fail: function () {
          console.log('跳转到welcome页面失败');
        }
      });
      return;
    }

   // this.waitUser();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    //注册回调函数
    // socketUtil.registCallBack(this.doSocket);
    app.globalData.socketCallBack = this.doSocket;
  },

  doSocket: function (res) {
    console.log('ready socket ' + res);
    let that = this;
    let wsDTO = res



    if (1001 === wsDTO.wsType) {
      clearInterval(this.data.timeWaitFun);
      let userInfo = wsDTO.data;
      let joinUsers = that.data.joinUsers;
      let joinCount = that.data.joinCount;

      for (let i = 0; i < joinUsers.length; i++) {
        if (joinUsers[i].openId == userInfo.openId) {
          console.log("用户重复参与" + userInfo.openId);
          return;
        }
      }

      joinUsers.push(userInfo);

      that.setData({ joinUsers: joinUsers, joinCount: joinCount + 1, showStart: '.show' });
    }

    if (1002 === wsDTO.wsType) {
      //获取答卷数据

      wx.setStorageSync('paperInfo', wsDTO);
      wx.reLaunch({
        url: '/pages/paper/paper?fromType=13&&model=1'
      })
    }

    if (1004 === wsDTO.wsType) {
      clearInterval(this.data.timeWaitFun);
      let userInfo = wsDTO.data;
      let joinUsers = that.data.joinUsers;
      let joinCount = that.data.joinCount;

      for (let i = 0; i < joinUsers.length; i++) {
        if (joinUsers[i].openId == userInfo.openId) {
          console.log("用户离开房间" + userInfo.openId);
          if (joinCount > 1) {
            joinCount -= 1;
          }

          joinUsers.splice(i, 1);
        }
      }

      that.setData({ joinUsers: joinUsers, joinCount: joinCount, showStart: '.show' });
    }

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    console.log('ready onUnload');
    clearInterval(this.data.timeWaitFun);
  },

  leaveRoom2: function () {
    let that = this;
    wx.request({
      url: cfg.host + cfg.mwurl.leaveRoom,
      data: {
        openId: wx.getStorageSync('loginUser').openId,
        roomTicket: wx.getStorageSync('roomTicket')
      },
      success: function (res) {
        console.log(res.data);
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      method: 'POST'
    })
  },

  leaveRoom: function () {
    let that = this;
    wx.showModal({
      title: '提示',
      content: '确定离开房间？',
      success: function (res) {
        if (res.confirm) {
          wx.request({
            url: cfg.host + cfg.mwurl.leaveRoom,
            data: {
              openId: wx.getStorageSync('loginUser').openId,
              roomTicket: wx.getStorageSync('roomTicket')
            },
            success: function (res) {
              console.log(res.data);
              wx.reLaunch({
                url: '/pages/home/home',
                success: function () {
                  console.log('跳转到home页面');
                }
              });
            },
            header: {
              'content-type': 'application/x-www-form-urlencoded' // 默认值
            },
            method: 'POST'
          })
        } else if (res.cancel) {

        }
      }
    })

  },

  joinRoom: function () {
    let that = this;
    if (that.data.joined) {
      wx.showToast({
        title: '已参与',
        icon: 'none',
        duration: 2000
      })

      return;
    }
    wx.request({
      url: cfg.host + cfg.mwurl.joinRoom,
      data: {
        // openId: wx.getStorageSync('loginUser').openId,
        openId: wx.getStorageSync('loginUser').openId,
        // nickName: app.globalData.userInfo.nickName,
        nickName: app.globalData.userInfo.nickName,
        // picUrl: app.globalData.userInfo.avatarUrl,
        picUrl: app.globalData.userInfo.avatarUrl,
        // roomTicket: wx.getStorageSync('roomTicket'),
        roomTicket: wx.getStorageSync('roomTicket'),
        model: 1
      },
      success: function (res) {
        console.log(res.data);

        if (res.data.code !== 1000) {
          let flag = res.data.message == '房间已过期';

          wx.showModal({
            title: '提示',
            content: res.data.message,
            showCancel: false,
            success: function (res) {
              if (res.confirm && flag) {
                wx.reLaunch({
                  url: '/pages/home/home'
                })
              } else if (res.cancel) {

              }
            }
          })
          return;
        }

        that.data.joined = true;
        that.waitUser();

        let joinUsers = that.data.joinUsers;

        for (let i = 0; i < res.data.data.length; i++) {
          let flag = false;
          for (let j = 0; j < joinUsers.length; j++) {
            if (joinUsers[j].openId == res.data.data[i].openId) {
              flag = true;
              break;
            }
          }

          if (!flag) {
            joinUsers.push(res.data.data[i]);
          }
          
        }

        that.setData({ joinUsers: joinUsers, joinCount: joinUsers.length, showStart: '.show'});
  
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      method: 'POST'
    })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})